#!/usr/bin/env python
#coding=utf-8


from flask_sqlalchemy import BaseQuery
from models.base import db
from models.model import Post


class PostQuery(BaseQuery):

    def __init__(self, db):
        super(Post, self).__init__(db)

    def get_post_by_id(self, id):
        return self.get(id)

    def get_post_list(self):
        return self.filter(Post.deleted == 0).all()

    def get_post_by_name(self, name):
        return self.filter(Post.post_name.ilike(name)).distinct().first()

    def get_post_per_page(self, page_id, per_page):
        return self.order_by(Post.post_create_time.desc()).paginate(page_id, per_page)

    def hottest(self):
        return self.order_by(Post.comment_count.desc(), Post.view_num.desc())

    def newpost(self):
        return self.order_by(Post.post_modified_time.desc())

    def search(self, keywords):
        criteria = []
        for keyword in keywords.split():
            keyword = '%' + keyword + '%'
            criteria.append(db.or_(Post.post_title.ilike(keyword),
                                   Post.post_content.ilike(keyword),
                                   Post.tags_name.ilike(keyword)))

        q = reduce(db.and_, criteria)

        return self.filter(q).distinct()

    def search_tag(self, keywords):
        criteria = []
        for keyword in keywords.split():
            keyword = '%' + keyword + '%'
            criteria.append(db.or_(Post.tags_name.ilike(keyword)))

        q = reduce(db.and_, criteria)

        return self.filter(q).distinct()